/**
 * 
 */
package com.antilia.infomaresme.pages.edit;

import java.util.List;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.tree.Tree;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.resource.ResourceReference;

import com.antilia.infomaresme.data.dao.interfaces.ICategoriesDao;
import com.antilia.infomaresme.data.dataobjects.Category;
import com.google.inject.Inject;

/**
 * @author Ernesto Reinaldo Barreiro (reiern70@gmail.com)
 *
 */
public abstract class AsignCategoryPanel extends Panel {

	private static final long serialVersionUID = 1L;
	
	@Inject
	private ICategoriesDao categoriesDao;

	/**
	 * 
	 */
	public AsignCategoryPanel(String id, List<Category> topLevel, IModel<String> root, IModel<String> text) {
		super(id);
		wrap(root);
		add(new Label("text", text));
		Form<Category> form = new Form<Category>("form");
		add(form);
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(root.getObject());
		add(rootNode, topLevel);
		TreeModel model = new DefaultTreeModel(rootNode);
		Tree tree = new Tree("tree", model) {
			
			private static final long serialVersionUID = 1L;

			@Override
			protected String renderNode(TreeNode node)
			{
				DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
				Object userObject = treeNode.getUserObject();
				if(userObject instanceof Category) {
					Category category = (Category)userObject;
					return category.getDescription();
				}
				return String.valueOf(treeNode.getUserObject());
			}
			
			
			@Override
			protected ResourceReference getCSS() {
				return null;
			}
			
			@Override
			protected void onNodeLinkClicked(AjaxRequestTarget target, TreeNode node) {
				if(node.getChildCount() == 0) {
					DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
					Category category = (Category)treeNode.getUserObject();
					AsignCategoryPanel.this.onCategorySelected(target, category);
				}
			}
		};
		form.add(tree);
	}
	
	protected abstract void onCategorySelected(AjaxRequestTarget target, Category category);
	
	private void add(DefaultMutableTreeNode parent, List<Category> sub)
	{
		for (Category obj : sub)
		{
			DefaultMutableTreeNode child = new DefaultMutableTreeNode(obj);
			parent.add(child);			
			List<Category> subSub = categoriesDao.findChildrem(obj);
			add(child, subSub);
		}
	}

	public ICategoriesDao getCategoriesDao() {
		return categoriesDao;
	}

	public void setCategoriesDao(ICategoriesDao categoriesDao) {
		this.categoriesDao = categoriesDao;
	}

}
